package net.tngou.db.netty;

import net.tngou.db.lucene.Config;
import net.tngou.db.util.I18N;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class TngouServer {

	
	 private int port=Integer.parseInt(System.getProperty("port", "8788"));;  
     
	 public TngouServer(int port) {  
	       
		 this.port = port;  
	 } 
	 
	public void run() throws InterruptedException {
		
		 EventLoopGroup bossGroup = new NioEventLoopGroup(10);
		 EventLoopGroup workerGroup = new NioEventLoopGroup();		 
		 try {
			 
			// Server服务启动器  
				 ServerBootstrap b = new ServerBootstrap();
				 b.group(bossGroup, workerGroup)
				 .channel(NioServerSocketChannel.class)			
//				 .handler(new LoggingHandler(LogLevel.INFO))
//				 .childHandler(new ServerInitializer())
				 .option(ChannelOption.SO_BACKLOG, 120)
				 .childOption(ChannelOption.SO_KEEPALIVE, true) // (6)
				  .childHandler(new ChannelInitializer<SocketChannel>() {
					@Override
					public void initChannel(SocketChannel ch) {
					ChannelPipeline p = ch.pipeline();
					 
					 p.addLast(new ObjectEncoder());
					 p.addLast( new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
				  	  p.addLast(new ServerHandler());
					}
					});
				 
				 ChannelFuture f = b.bind(port).sync();
				  
				 f.channel().closeFuture().sync();
			
			 } finally {
			 workerGroup.shutdownGracefully();
			 bossGroup.shutdownGracefully();
			 }
	}
	
	public static void main(String[] args) throws Exception {  

		int port =  Config.getInstance().getPort();
         System.out.println(I18N.getValue("start",port+""));
        new TngouServer(port).run();  
       
    } 
}
